package util

import (
	"log"

	"github.com/casbin/casbin/v2"
	gormadapter "github.com/casbin/gorm-adapter/v3"

	"awesomeProject/global"
)

type SEnforcer struct{}

var (
	enforcer *casbin.Enforcer
)

// NewEnforcer enforcer实例
func (r *SEnforcer) newEnforcer() *casbin.Enforcer {
	a, err := gormadapter.NewAdapterByDB(global.Gorm)
	if err != nil {
		log.Fatalf("error: adapter: %s", err)
	}
	enforcer, _ = casbin.NewEnforcer(global.Config.CasbinConf.ModelPath, a)

	err = enforcer.LoadPolicy()
	if err != nil {
		log.Fatalf("error: loadPolicy: %s", err)
	}

	return enforcer
}

func (r *SEnforcer) Enforce(rvals ...interface{}) (bool, error) {
	enforcer := r.newEnforcer()
	return enforcer.Enforce(rvals...)
}

// AddRolesForUser 为用户附加角色
func (r *SEnforcer) AddRolesForUser(user string, roles []string, domain ...string) (bool, error) {
	enforcer := r.newEnforcer()
	return enforcer.AddRolesForUser(user, roles, domain...)
}

// RemoveFilteredPolicy 删除权限策略
func (r *SEnforcer) RemoveFilteredPolicy(fieldIndex int, fieldValues ...string) (bool, error) {
	enforcer := r.newEnforcer()
	return enforcer.RemoveFilteredPolicy(fieldIndex, fieldValues...)
}

// AddPolicies 添加权限策略
func (r *SEnforcer) AddPolicies(roles [][]string) (bool, error) {
	enforcer := r.newEnforcer()
	return enforcer.AddPolicies(roles)
}

// GetRolesForUser 获取用户角色
func (r *SEnforcer) GetRolesForUser(name string, domain ...string) ([]string, error) {
	enforcer := r.newEnforcer()
	return enforcer.GetRolesForUser(name, domain...)
}

func (r *SEnforcer) GetFilteredPolicy(fieldIndex int, fieldValues ...string) [][]string {
	enforcer := r.newEnforcer()
	return enforcer.GetFilteredPolicy(fieldIndex, fieldValues...)
}

func (r *SEnforcer) DeleteRolesForUser(user string, domain ...string) (bool, error) {
	enforcer := r.newEnforcer()
	return enforcer.DeleteRolesForUser(user)
}
